package cn.ipanel.bigdata;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * @author lzz
 * @environment IntelliJ IDEA 2020.3.1
 * @projectName bigdata_shanxi
 * @date 2023/04/03 09:42
 * @description: 文件编码格式判断：
 *                      ANSI：　　　　　　　　   无格式定义；
 *                      Unicode： 　　　　　　  前两个字节为FFFE；
 *                      Unicode big endian：　前两字节为FEFF；　
 *                      UTF-8：　 　　　　　　  前两字节为EFBB；
 */
public class FileEncodeJudge {

    private File file;

    public FileEncodeJudge(File file) {
        this.file = file;
    }

    public FileEncodeJudge(String path) {
        file = new File(path);
    }

    public String getCharset() {
        File file = this.file;

        String charset = "GBK";
        byte[] first3Bytes = new byte[3];
        BufferedInputStream bis = null;
        try {
            //boolean checked = false;
            bis = new BufferedInputStream(new FileInputStream(file));
            bis.mark(0);
            int read = bis.read(first3Bytes, 0, 3);
            if (read == -1) {
                return charset;
            }
            System.out.println("first3Bytes: " + Integer.toHexString(first3Bytes[0]) + " " + Integer.toHexString(first3Bytes[1]) + " " + Integer.toHexString(first3Bytes[2]));
            System.out.println("first3Bytes: " + first3Bytes[0] + " " + first3Bytes[1] + " " + first3Bytes[2]);
            if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
                charset = "UTF-16LE";
                //checked = true;
            } else if (first3Bytes[0] == (byte) 0xFE
                    && first3Bytes[1] == (byte) 0xFF) {
                charset = "UTF-16BE";
                //checked = true;
            } else if (first3Bytes[0] == (byte) 0xEF
                    && first3Bytes[1] == (byte) 0xBB
                    && first3Bytes[2] == (byte) 0xBF) {
                charset = "UTF-8";
                //checked = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return charset;
    }

    public static void main(String[] args) {
        FileEncodeJudge fer = new FileEncodeJudge("D:/文档/陕西网关/现场文档/区域底量/county20230331160000.txt");
        System.out.println(fer.getCharset());
    }

}
